package com.ttsx.core.common.interceptor;

/**
 * @author wb
 * @since 2025-11-06
 */

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttsx.core.common.constant.CacheConstants;
import com.ttsx.core.common.util.JwtUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Jwt拦截器
 */
public class JwtInterceptor implements HandlerInterceptor {

    private RedisTemplate<String, Object> redisTemplate;

    public JwtInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // options 请求不拦截
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        // 封装消息
        Map<String, Object> map = new HashMap<>();

        // 获取请求头中的 token
        String authorization = request.getHeader("Authorization");
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            map.put("code", 401);
            map.put("message", "token为空或格式错误");
            sendResponse(response, map);
            return false;
        }


        String token = authorization.substring(7);

        try {
            // 验证令牌
            JwtUtils.verifyToken(token);

            // 验证用户是否登录
            Boolean b = redisTemplate.hasKey(CacheConstants.USER_KEY + token);
            if (Boolean.FALSE.equals(b)) {
                map.put("message", "登录状态失效!");
                map.put("code", 401);

                sendResponse(response, map);
                return false;
            }

            return true;
        } catch (SignatureVerificationException e) {
            map.put("message", "无效签名");
        } catch (TokenExpiredException e) {
            map.put("message", "token过期");
        } catch (AlgorithmMismatchException e) {
            map.put("message", "算法不匹配");
        } catch (Exception e) {
            map.put("message", "token无效");
        }

        // 设置状态
        map.put("code", 401);
        sendResponse(response, map);

        // 拦截
        return false;
    }


    private void sendResponse(HttpServletResponse response, Map<String, Object> map) throws Exception {
        // 将 map 转成 json
        String json = new ObjectMapper().writeValueAsString(map);

        // 设置响应编码格式
        response.setContentType("application/json;charset=utf-8");

        // 打印输出流
        PrintWriter pw = response.getWriter();

        // 输出数据
        pw.println(json);

        // 关闭流
        pw.close();
    }
}
